import VueRouter from 'vue-router'
import Vue from 'vue'

Vue.use(VueRouter)
const routes = []

export const filterRoutes = function (routes) {
  const resultRoutes = []
  routes.forEach(route => {
    // route.path = `/${process.env.VUE_APP_NAME}${route.path}`;
    if (route.url && route.url.indexOf(`/${process.env.VUE_APP_NAME}`) !== 0) {
      return
    }
    if (!route.url && route.children) { // 没有ulr的父级菜单
      resultRoutes.push(...filterRoutes(route.children))
      return
    }
    if (!route.url) {
      return
    }
    route.path = route.url
    // eslint-disable-next-line
    route.component = () => {
      const path = route.url.replace(`/${process.env.VUE_APP_NAME}`, '')
      return import('@/views' + path)
    }
    route.name = route.text
    route.meta = { ...route.meta, text: route.text, id: route.id, pids: route.pids || [], pidsByPath: route.pidsByPath || false }
    if (route.children && route.children instanceof Array) {
      route.children = filterRoutes(route.children)
    }
    resultRoutes.push(route)
    return route
  })
  // console.log(`子应用${process.env.VUE_APP_NAME}的路由是`, resultRoutes)
  return resultRoutes
}

// 路径匹配子应用名称
const createRouter = () =>
  new VueRouter({
    mode: 'hash',
    routes: routes
  })

export const router = createRouter()

export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}
